const jwt = require('jsonwebtoken')
const {readFileSync} = require('fs')
const path = require('path')
const xy = require('../utils/xy')

module.exports = (req, resp, next) => {
    if(req.url === '/api/user/login') {
        next()
        return
    }
    if(req.url.startsWith('/uploads')) {
        next()
        return
    }
    if(req.url === '/api/uploads') {
        next()
        return
    }
    // 规定令牌必须从请求头传递来
    if(!req.headers.authorization) {
        xy(resp, 406, '缺少身份验证！')
        return
    }
    // 验证令牌真伪 - 是否能解开
    let configFilePath = path.join(__dirname, '../', 'config', 'config.json')
    let salt = JSON.parse(readFileSync(configFilePath, 'utf-8')).tokenSalt
    jwt.verify(req.headers.authorization, salt, (err, decoded) => {
        if(err) {
            xy(resp, 407, '身份验证失败！')
            return
        }
        // 验证令牌有效期
        let {startTime, expires} = decoded
        if(startTime + expires < +new Date()) {
            xy(resp, 408, '登录过期！')
            return
        }
        next()
    })
}